<template>
  <!-- 新增部门的弹层 -->
  <el-dialog :title="showTitle" :visible="showDialog" @close="btnCancel">
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form
      ref="deptForm"
      label-width="120px"
      :model="formData"
      :rules="rules"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="formData.name"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="formData.code"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="formData.manager"
          style="width: 80%"
          placeholder="请选择"
          @focus="getEmployeeSimple"
          @blur="checkManager"
        >
          <el-option
            v-for="person in people"
            :key="person.id"
            :label="person.username"
            :value="person.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="formData.introduce"
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <el-row slot="footer" type="flex" justify="center">
      <!-- 列被分为24 -->
      <el-col :span="6">
        <el-button
          type="primary"
          size="small"
          @click="addDepartment"
        >确定</el-button>
        <el-button size="small" @click="btnCancel">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import {
  getDepartments,
  addDepartments,
  getDepartDetail,
  updateDepartments
} from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    node: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    // 注意校验规则 编辑和新增略有不同  编辑要保证排除自己名称和自己的id，编辑找出与自己同级 =》 自己 pid === item.pid
    const checkNameRepeat = async(rule, value, callback) => {
      // 同级部门不可以同名
      const { depts } = await getDepartments()
      let isRepeat
      if (this.formData.id) {
        isRepeat = depts
          .filter((item) => item.pid === this.node.pid)
          .some((item) => item.name === value && item.id !== this.formData.id)
      } else {
        isRepeat = depts
          .filter((item) => item.pid === this.node.id)
          .some((item) => item.name === value)
      }
      isRepeat ? callback(new Error('同级部门名称不可重复！')) : callback()
    }
    const checkCodeRepeat = async(rule, value, callback) => {
      const { depts } = await getDepartments()
      const isRepeat = depts.some(
        (item) => item.code === value && item.id !== this.node.id
      )
      isRepeat ? callback(new Error('部门编号必须是唯一的!')) : callback()
    }
    return {
      formData: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      rules: {
        name: [
          { required: true, message: '该项不能为空', trigger: 'blur' },
          {
            trigger: 'blur',
            min: 1,
            max: 50,
            message: '部门名称要求1-50个字符'
          },
          { validator: checkNameRepeat, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '该项不能为空', trigger: 'blur' },
          {
            trigger: 'blur',
            min: 1,
            max: 50,
            message: '部门编码要求1-50个字符'
          },
          { validator: checkCodeRepeat, trigger: 'blur' }
        ],
        manager: [
          {
            required: true,
            message: '该项不能为空',
            trigger: ['blur', 'change']
          }
        ],
        introduce: [
          { required: true, message: '该项不能为空', trigger: 'blur' },
          {
            trigger: 'blur',
            min: 1,
            max: 300,
            message: '部门介绍要求1-300个字符'
          }
        ]
      },
      people: []
    }
  },
  computed: {
    showTitle() {
      return this.formData.id ? '编辑部门' : '添加部门'
    }
  },
  methods: {
    async getDepartDetail(id) {
      this.formData = await getDepartDetail(id)
    },
    // 解决select下拉框无法触发 rules 校验规则问题
    checkManager() {
      this.$refs.deptForm.validateField('manager')
    },
    btnCancel() {
      this.$emit('update:showDialog', false)
      // 重置表单
      this.$refs.deptForm.resetFields()
      // 由于是根据formData中是否存在id来判断是编辑还是添加 重置表单并不能重置编辑中重新赋值的formData 所以要手动重置formData
      this.formData = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
    },
    addDepartment() {
      console.log(this.formData)
      this.$refs.deptForm.validate(async(isOK) => {
        if (isOK) {
          // 根据formData中是否有id判断是添加还是编辑
          if (this.formData.id) {
            await updateDepartments(this.formData)
            this.$message.success('修改成功！')
          } else {
            await addDepartments({ ...this.formData, pid: this.node.id })
            this.$message.success('添加成功！')
          }
          // 通知父页面更新数据
          this.$emit('addDepts')
          // 固定写法 配合父组件 .sync 修饰符，方便修改 接收父组件的 props 值
          this.$emit('update:showDialog', false)
        }
      })
    },
    async getEmployeeSimple() {
      const res = await getEmployeeSimple()
      console.log('员工简单列表', res)
      if (res.length > 0) {
        this.people = res
      }
    }
  }
}
</script>

<style>
</style>
